package client.comm.commlib.comm_ui.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import client.comm.commlib.R
import client.comm.commlib.base.BaseAdapter
import client.comm.commlib.comm_ui.bean.ImageFolder
import com.bumptech.glide.RequestManager
import com.bumptech.glide.request.RequestOptions

class ImageFolderAdapter(context: Context, requerst: RequestManager) : BaseAdapter<ImageFolder>(
    context,
    object : DiffUtil.ItemCallback<ImageFolder>() {
        override fun areItemsTheSame(oldItem: ImageFolder, newItem: ImageFolder): Boolean {
            return oldItem.name == newItem.name
        }

        override fun areContentsTheSame(oldItem: ImageFolder, newItem: ImageFolder): Boolean {
            return oldItem == newItem
        }

    }
) {
    var mListener: OnItemClickListener? = null
    val loder: RequestManager

    init {
        loder = requerst
    }

    fun setOnItemClickListener(listener: OnItemClickListener?) {
        this.mListener = listener
    }

    fun resetItem(items: List<ImageFolder?>?) {
        if (items != null) {
            submitList(items)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return FolderViewHolder(layoutInflater.inflate(R.layout.item_list_folder, parent, false))
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val item = getItem(position)
        val h = holder as FolderViewHolder
        h.tv_name.text = item!!.name
        h.tv_size.text = String.format("(%s)", item.images.size)
        loder.load(item.imgUri)
            .apply(RequestOptions().error(R.mipmap.ic_default_image).centerCrop())
            .into(h.iv_image)
        holder.itemView.setOnClickListener {
            if (mListener != null) {
                mListener!!.onItemClick(position)
            }
        }
    }

    private class FolderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var iv_image: ImageView
        var tv_name: TextView
        var tv_size: TextView

        init {
            iv_image = itemView.findViewById<View>(R.id.iv_folder) as ImageView
            tv_name = itemView.findViewById<View>(R.id.tv_folder_name) as TextView
            tv_size = itemView.findViewById<View>(R.id.tv_size) as TextView
        }
    }

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }
}